<template>
  <div class="confirm-order">
    <div class="header">
      <!-- <van-icon name="arrow-left" size="24" @click="goBack" /> -->
      <van-icon name="arrow-left" size="24" @click="$router.back()" />
      <div class="title">修改订单</div>
    </div>
    <div class="service-guarantee">
      服务保障
      <span>明码标价 | 未上门随时退 | 90天质保</span>
    </div>


    <div class="address-time">
      <div class="address" @click="showAddressEditor = true">
        <van-icon name="location-o" size="24" />
        <span>{{ formattedAddress }}</span>
        <van-icon name="arrow" size="24" />
      </div>

      <div class="time" @click="handleTimePicker">
        <van-icon name="clock-o" size="24" />
        <!-- <span>{{ formattedTime }}</span> -->
        <span>{{ formattedTime || orderDetail[0].serviceTime }}</span>
        <van-icon name="arrow" size="24" />
      </div>
    </div>


    <div class="service-item">
      <div class="item-info">
        <div class="item-name">{{ category.categories.categoryName }}</div>
        <div class="item-count">
          <van-icon name="minus" size="24" @click="decreaseCount" />
          <span>{{ orderDetail[0].itemQuantity }}</span>
          <van-icon name="plus" size="24" @click="increaseCount" />
        </div>
      </div>
    </div>

    <div class="item-details">

      <div class="form-section">
        <van-field v-model="category.categories.categoryName" is-link readonly label="物品类型" placeholder="请选择物品类型" @click="handleTypeClick"
          label-class="required-label" :disabled="loadingTypes || itemTypes.length === 0"
          :clickable="!loadingTypes && itemTypes.length > 0" />
          
        <van-popup v-model:show="showPicker" destroy-on-close round position="bottom">
          <van-picker :model-value="pickerValue" :columns="itemTypes" @cancel="showPicker = false"
            @confirm="onItemTypeConfirm" :loading="loadingTypes" />
        </van-popup>
      </div>

      <div class="description">
        如有多套或不同类型产品的服务需求，可通过购物车功能进行添加~
      </div>

      <div class="image-upload">
        <span>*物品图片</span>
        <van-uploader v-model="uploadedImages" :after-read="handleImageUpload" :max-count="9" preview-size="80px"
          preview-full-image>
          <template #tip>
            <span v-if="uploadedImages.length">已上传{{ uploadedImages.length }}张</span>
          </template>
        </van-uploader>
      </div>
      <div class="requirement">
        <div class="requirement-input">
          <span>需求说明</span>
          <van-field v-model="orderDetail[0].specialRequirements" rows="2" autosize type="textarea"
            placeholder="如有特殊需求，请在此说明" />
        </div>
        <div class="example">示例：仅周末有时间，请师傅带齐工具，按时上门。</div>
      </div>
    </div>
    <div class="submit-button">
      <!-- <van-button type="primary" block @click="handleSubmit" :disabled="!isFormComplete">修改订单</van-button> -->
      <van-button type="primary" block @click="handleSubmit" :disabled="!isFormComplete">修改订单</van-button>
    </div>

    <!-- 地址编辑弹窗 -->
    <van-popup v-model:show="showAddressEditor" position="bottom" class="address-editor-popup">
      <div class="address-editor-header">
        <span>编辑地址</span>
        <span class="note">个人信息仅用于发布需求，隐私信息完全保密</span>
      </div>
      <div class="address-editor-content">
        <div class="map-address">

          <div class="map-address-detail">
            <div class="detail-address">
              <van-icon name="edit" size="24" />
              <span>详细地址</span>
              <van-field v-model="address.addresss" placeholder="请输入详细地址"
                :rules="[{ required: true, message: '请填写详细地址' }]" />
            </div>
            <div class="region-address">
              <span>所在地区</span>
              <span>江西省南昌市青山湖区艾溪湖管理处</span>
            </div>
          </div>
        </div>
      </div>
      <div class="contact-info">
        <div class="contact-name">

          <van-field v-model="orderDetail[0].contactName" placeholder="联系人姓名"
            :rules="[{ required: true, message: '请填写联系人姓名' }]" />

          <div class="gender-buttons">
            <van-button type="primary" size="small" :plain="address.gender !== '先生'" @click="address.gender = '先生'">
              先生
            </van-button>
            <van-button type="primary" size="small" :plain="address.gender !== '女士'" @click="address.gender = '女士'">
              女士
            </van-button>
          </div>

          <div class="contact-phone">
            <van-field v-model="orderDetail[0].contactPhone" placeholder="联系人电话" type="tel" :rules="[
              { required: true, message: '请填写联系电话' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
            ]" />

          </div>
        </div>
      </div>
      <div class="address-editor-footer">
        <van-button type="danger" size="large" @click="deleteAddress">删除</van-button>
        <van-button type="primary" size="large" @click="saveAddress">保存</van-button>
      </div>
    </van-popup>
    <van-popup v-model:show="timePickerVisible" position="bottom" class="time-picker-popup">
      <div class="time-picker-header">
        <span>您期望上门服务时间</span>
        <span class="note">师傅接单后电话与您确认最终上门时间</span>
      </div>
      <div class="time-picker-content">
        <div class="time-date-list">
          <div v-for="(date, index) in timeOptions" :key="index" :class="{ active: selectedDateIndex === index }"
            @click="selectDate(index)">
            {{ date.label }}
          </div>
        </div>
        <div class="time-slot-list">
          <div v-for="(slot, slotIndex) in timeOptions[selectedDateIndex].slots" :key="slotIndex"
            :class="{ active: selectedSlotIndex === slotIndex }" @click="selectSlot(slotIndex)">
            {{ slot }}
          </div>
        </div>
      </div>
      <div class="time-picker-footer">
        <van-button type="primary" block @click="confirmTime">确定</van-button>
      </div>
    </van-popup>

  </div>
</template>

<script setup name="ConfirmOrder">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { emitter } from '../utils/eventBus'
import { showToast, showConfirmDialog,showFailToast } from 'vant'
import {
  getaddressById, getaddAddress, uploadImageApi, getCategoryById,getDetailsByOrderId,
  getFullOrderDetail, getOrdersByUserWithService, findOrderByOrderId, getServiceById, getAddressByAddressId, updateAddress,
  getFindAllTypes, updateOrdetail
} from '../api'
import { useUserInfoStore } from '../stores/userInfo'

const route = useRoute();
// const router = useRouter();

const orderId = ref(null);
const order = ref([]);
const address = ref({
  addresss: '',
  id: '',
  status: '',
  gender: '先生',
  userId: ''
});

const service = ref({
  services: {
    serviceId: null,
    categoryId: '',
    serviceName: '',
    price: null,
    description: ''
  }
});
const category = ref({
  categories: {
    categoryId: null,
    categoryName: '',
  }
});

const isFormComplete = computed(() => {
    return uploadedImages.value.length > 0
})

const orderDetail = ref([
  {
    addressId: null,
    categoryId: null,
    contactName: '',
    contactPhone: '',
    detailId: null,
    itemImages: '',
    itemQuantity: 0,
    orderId: null,
    serviceId: null,
    serviceTime: null,
    specialRequirements: '',
    updateTime: ''
  }
]);


// 获取订单列表
const fetchOrderDetail = async (orderId) => {
  try {
    // loading.value = true;
    // console.log('111', orderId);
    //订单表
    const retOrder = await findOrderByOrderId(orderId);
    order.value = retOrder
    // console.log(order.value.status);

    //订单详情表
    const retOrderDetail = await getDetailsByOrderId(orderId);
    orderDetail.value = retOrderDetail;

    //服务表
    // console.log('bb', order.value.serviceId);
    const retService = await getServiceById(order.value.serviceId);
    service.value = retService

    //分类表
    const retCategory = await getCategoryById(orderDetail.value[0].categoryId);
    category.value = retCategory

    //地址表
    const retAddress = await getAddressByAddressId(orderDetail.value[0].addressId)
    address.value = { ...retAddress, gender: '先生' }

    // console.log('order:', order.value);
    // console.log('orderDetail:', orderDetail.value);
    // console.log('service:', service.value);
    // console.log('category:', category.value);
    // console.log('address:', address.value);
  } catch (err) {
    console.error('获取订单失败:', err);
    err.value = '加载订单失败，请重试';
    showToast({
      type: 'fail',
      message: '加载失败',
      duration: 1500,
    });
  } finally {
    // loading.value = false;
  }
};



const formattedTime = ref()
const router = useRouter()
const useAddress = ref("绿地集团写字楼")
const showAddressEditor = ref(false)
const UserInfoStore = useUserInfoStore()
const addressDetails = ref({
  detailedAddress: '',
  contactName: '',
  gender: '先生',
  contactPhone: '',
  isDefaultAddress: false
})
//获取分类
// const service=ref()
// const categoryName = ref("沙发安装")
// const getCategory = async () => {
//   console.log(category.categories.categoryName);
//   // let category = await getCategoryById(service.value.categoryId)
//   // categoryName.value = category.categories.categoryName
//   console.log(category.categories.categoryName);
// }
//获取默认地址
const defaultAddress = ref()
const AddressId = ref()
//上传地址
const addAddress = ref({
  "id": '',
  "userId": null,
  "addresss": "",
  "status": 1
})

const formattedAddress = computed(() => {
  return `${address.value.addresss} (${orderDetail.value[0].contactName} ${address.value.gender} ${orderDetail.value[0].contactPhone})`
})

const showTimePicker = ref(false)
const useThisAddress = () => {
  addressDetails.value.detailedAddress = useAddress.value;
  showToast('地址已应用');
}
const saveAddress = async () => {
  if (!address.value.addresss ||
    !orderDetail.value[0].contactName ||
    !orderDetail.value[0].contactPhone) {
    showToast('请完善地址信息');
    return;
  }
  // if (addressDetails.value.isDefaultAddress) {
  //   addAddress.value.status = 0
  // }
  // console.log('111');
  addAddress.value.id = orderDetail.value[0].addressId
  addAddress.value.userId = orderDetail.value[0].userId
  addAddress.value.addresss = address.value.addresss
  // console.log('地址', addAddress.value.addresss);
  try {
    // console.log('地址：', addAddress.value);
    // let retrunId = await getaddAddress(addAddress.value)
    // console.log('addAddress.value', addAddress.value);
    let retrunId = await updateAddress(addAddress.value)
    AddressId.value = retrunId
    // console.log(AddressId.value);
    // console.log('retrunUserId', retrunId);
    showToast('地址更新成功');
    showAddressEditor.value = false;
  } catch (e) {
    console.log("保存失败", e);
  }
};

const deleteAddress = () => {
  showConfirmDialog({
    title: '确认删除',
    message: '确定要删除这个地址吗？',
  }).then(() => {
    // addressDetails.value = {
    //   detailedAddress: '',
    //   contactName: '',
    //   gender: '先生',
    //   contactPhone: '',
    //   isDefaultAddress: false
    // }
    address.value.addresss = '',
      orderDetail.value[0].contactName = '',
      orderDetail.value[0].contactPhone = '',
      showToast('地址已删除')

    // console.log('order:', order.value);
    // console.log('orderDetail:', orderDetail.value);
    // console.log('service:', service.value);
    // console.log('category:', category.value);
    // console.log('address:', address.value);
    showAddressEditor.value = false

  })
}

const itemCount = ref(1)

const decreaseCount = () => {
  if (orderDetail.value[0].itemQuantity > 1) {
    orderDetail.value[0].itemQuantity--
  }
}

const increaseCount = () => {
  orderDetail.value[0].itemQuantity++
}

const showItemTypePicker = ref(false)

const selectedItemType = ref('')

const onItemTypeConfirm = (value) => {
  // console.log('value', value.selectedOptions);
  // selectedItemType.value = value.selectedOptions[0].text;
  // category.categoryName = value.selectedOptions[0].text;
  // console.log(category);

  category.value.categories.categoryName = value.selectedOptions[0].text; 
  // console.log('111',value.selectedOptions[0].value);
  // console.log('category.categoryName',category.categoryName);
  // console.log(category);
  showPicker.value = false
}

const uploadedImages = ref([])
const Images = ref([])
const handleImageUpload = async (file) => {
  try {
    // 如果是多文件上传(file是数组)
    if (Array.isArray(file)) {
      const uploadPromises = file.map(item => uploadImageApi(item.file))
      const results = await Promise.all(uploadPromises)
//       console.log('results',results);
// console.log('uploadPromises',uploadPromises);
      results.forEach(response => {
        if (response && response.url) {
          uploadedImages.value.push({
            url: response.url,
            status: 'done',
            uid: Date.now() + Math.random().toString(36).substr(2, 9)
          })
        }
      })

      showToast(`成功上传${results.length}张图片`)
      return
    }

    // 单文件上传
    const response = await uploadImageApi(file.file)

// console.log('response',response);
// console.log('response.url',response.url);
    if (response && response.url) {
      Images.value.push({
        url: response.url,
        status: 'done',
        uid: Date.now() + Math.random().toString(36).substr(2, 9)
      })
      showToast('图片上传成功')
      // console.log('uploadedImages',uploadedImages);
    } else {
      file.status = 'failed'
      file.message = '上传失败'
      showToast('图片上传失败')
    }
  } catch (error) {
    console.error('Upload error:', error)
    showToast('图片上传失败')
    file.status = 'failed'
    file.message = error.message || '上传出错'
  }
}
const specialRequirements = ref('')


const handleSubmit = () => {

  const orderData = {
    detailId: orderDetail.value[0].detailId,
    addressId: orderDetail.value[0].addressId,
    categoryId: category.value.categories.categoryId,
    contactName: orderDetail.value[0].contactName,
    contactPhone: orderDetail.value[0].contactPhone,
    itemImages: Images.value[0].url,
    itemQuantity: orderDetail.value[0].itemQuantity,
    orderId: order.value.orderId,
    userId: orderDetail.value[0].userId,
    serviceId: service.value.services.serviceId,
    serviceTime: formattedTime.value || orderDetail.value[0].serviceTime,
    specialRequirements: orderDetail.value[0].specialRequirements,
    updateTime: formatDateTime(new Date())
  }

  // console.log('提交订单:', orderData)
  updateOrdetail(orderData)
  showToast('订单提交成功')
  router.back()
}

function formatDateTime(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const confirmTime = () => {


  const selectedDate = timeOptions.value[selectedDateIndex.value];
  const selectedSlot = selectedDate.slots[selectedSlotIndex.value];
  formattedTime.value = `${selectedDate.label} ${selectedSlot}`;
  // console.log('formattedTime',formattedTime);
  // console.log('formattedTime',formattedTime.value);
  timePickerVisible.value = false;
};
const timeOptions = ref([
  {
    label: '今天 07-23',
    slots: ['19:00-20:00', '20:00-21:00', '21:00-22:00']
  },
  {
    label: '明天 07-24',
    slots: ['19:00-20:00', '20:00-21:00', '21:00-22:00']
  },
  {
    label: '后天 07-25',
    slots: ['19:00-20:00', '20:00-21:00', '21:00-22:00']
  },
  {
    label: '周六 07-26',
    slots: ['19:00-20:00', '20:00-21:00', '21:00-22:00']
  },
  {
    label: '周日 07-27',
    slots: ['19:00-20:00', '20:00-21:00', '21:00-22:00']
  },
  {
    label: '周一 07-28',
    slots: ['19:00-20:00', '20:00-21:00', '21:00-22:00']
  }
]);
const selectedDateIndex = ref(0);
const selectedSlotIndex = ref(0);
const timePickerVisible = ref(false);
const handleTimePicker = () => {
  timePickerVisible.value = true;
};

const selectDate = (index) => {
  selectedDateIndex.value = index;
  selectedSlotIndex.value = 0;
};

const selectSlot = (index) => {
  selectedSlotIndex.value = index;
}


const handleTypeClick = () => {
    if (loadingTypes.value) {
        showToast('服务类型正在加载，请稍候...');
        return;
    }
    if (loadTypeError.value) {
        showToast('重新尝试加载服务类型...');
        fetchItemTypes();
        return;
    }
    if (itemTypes.value.length > 0) {
        if (selectedTypeId.value) {
            const index = itemTypes.value.findIndex(item => item.value === selectedTypeId.value);
            if (index !== -1) {
                pickerValue.value = [itemTypes.value[index].value];
            }
        }
        showPicker.value = true;
    } else {
        showFailToast('暂无可用的服务类型');
    }
};

const itemTypes = ref([]);
const itemTypeValue = ref('');
const showPicker = ref(false);
const pickerValue = ref([]);
const loadingTypes = ref(true);
const loadTypeError = ref(false);
const selectedTypeId = ref('');
const fetchItemTypes = async () => {
    try {
        loadingTypes.value = true;
        loadTypeError.value = false;
        const response = await getFindAllTypes();
        const typesData = response.data || response;

        if (Array.isArray(typesData) && typesData.length > 0) {
            itemTypes.value = typesData.map(type => ({
                text: type.categoryName,
                value: type.categoryId,
                raw: type
            }));
            showToast(`成功加载 ${itemTypes.value.length} 种服务类型`);
        } else {
            loadTypeError.value = true;
            showFailToast('未获取到有效服务类型数据');
        }
    } catch (error) {
        loadTypeError.value = true;
        itemTypes.value = [];
        showFailToast('加载服务类型失败，请重试');
    } finally {
        loadingTypes.value = false;
    }
};

// 初始化加载
onMounted(() => {
  orderId.value = route.query.id; // 获取参数
  // console.log('接收到的订单ID:', orderId.value);
  fetchOrderDetail(orderId.value);
  fetchItemTypes();
  // getCategory()
});
</script>


<style scoped>
.confirm-order {
  padding-bottom: 80px;
}

.header {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f5f5f5;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 18px;
  font-weight: bold;
}

.service-guarantee {
  padding: 10px 15px;
  font-size: 12px;
  color: #666;
  background-color: #f9f9f9;
  display: flex;
  justify-content: space-between;
}

.address-time {
  margin: 15px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.address,
.time {
  padding: 15px;
  display: flex;
  align-items: center;
  background-color: white;
}

.address {
  border-bottom: 1px solid #f5f5f5;
}

.address span,
.time span {
  flex: 1;
  margin: 0 10px;
}

.service-item {
  margin: 15px;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.item-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-count {
  display: flex;
  align-items: center;
}

.item-count span {
  margin: 0 10px;
}

.item-details {
  margin: 15px;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.type,
.image-upload,
.requirement {
  margin-bottom: 15px;
}

.type span:first-child,
.image-upload span {
  color: #ee0a24;
}

.description {
  font-size: 12px;
  color: #999;
  margin: 10px 0;
}

.upload-icon {
  margin-top: 10px;
  width: 80px;
  height: 80px;
  border: 1px dashed #ccc;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #999;
}

.requirement-text {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

.example {
  margin-top: 5px;
  font-size: 12px;
  color: #999;
}

.progress {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.submit-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px;
  background-color: white;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

.address-editor-popup {
  height: 80%;
}

.address-editor-header {
  padding: 15px;
  text-align: center;
  position: relative;
}

.address-editor-header .note {
  display: block;
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.address-editor-content {
  padding: 15px;
}

.map-address-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.detail-address,
.region-address {
  margin-bottom: 15px;
}

.contact-name,
.contact-phone {
  display: flex;
  margin-bottom: 15px;
}

.gender-buttons {
  display: flex;
  margin-left: 15px;
}

.gender-buttons .van-button {
  margin-right: 5px;
}

.default-address {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.address-editor-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
}

.address-editor-footer .van-button {
  flex: 1;
  border-radius: 0;
}

.time-picker-popup {
  width: 100%;
}

.requirement-input {
  margin-bottom: 10px;
}






.time-picker-popup {
  background-color: white;
  border-radius: 16px 16px 0 0;
  padding: 16px;
}

.time-picker-header {
  margin-bottom: 16px;
}

.time-picker-header .note {
  color: #666;
  font-size: 14px;
}

.time-date-list {
  display: flex;
  overflow-x: auto;
  margin-bottom: 16px;
}

.time-date-list div {
  padding: 8px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  margin-right: 8px;
  cursor: pointer;
}

.time-date-list div.active {
  background-color: #ee0a24;
  color: white;
  border-color: #ee0a24;
}

.time-slot-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
}

.time-slot-list div {
  padding: 8px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  text-align: center;
  cursor: pointer;
}

.time-slot-list div.active {
  background-color: #ee0a24;
  color: white;
  border-color: #ee0a24;
}

.time-picker-footer {
  margin-top: 24px;
}
</style>